<template>
  <div style="text-align: left">
    <el-form label-position="top" :rules="username_login_rules" label-width="80px" :model="loginForm">
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入手机号或者用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button @click="login" style="width: 100%;color: white;background-color: #122147">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUser, userNameLogin } from '../api/index'
export default {
  name: 'UsernameLogin',
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      username_login_rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      // 登录
      userNameLogin(this.loginForm.username, this.loginForm.password).then(({ data }) => {
        if (data.code === 0) {
          // 登录成功
          this.$message.success(data.data)
          // 更新用户的信息
          getUser().then(({ data }) => {
            this.$store.state.user = data.data
          })
          this.$router.push({ path: '/' })
        } else {
          this.$message.error(data.msg)
        }
      }).catch((res) => {
        console.log(res)
      })
    }
  }
}
</script>

<style scoped>

</style>
